package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.example.springboot.common.Result;
import org.example.springboot.entity.*;
import org.example.springboot.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class OrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private LogisticsMapper logisticsMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private LogisticsService logisticsService;

    /**
     * 生成订单号
     * 格式：年月日时分秒 + 用户ID后4位 + 4位随机数
     * @param userId 用户ID
     * @return 订单号
     */
    private String generateOrderNo(Long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timeStr = now.format(formatter);
        
        // 用户ID后4位，不足4位前面补0
        String userIdStr = String.format("%04d", userId % 10000);
        
        // 4位随机数
        Random random = new Random();
        String randomStr = String.format("%04d", random.nextInt(10000));
        
        // 组合订单号
        return timeStr + userIdStr + randomStr;
    }

    public Result<?> createOrder(Order order) {
        try {
            // 检查商品库存
            Product product = productMapper.selectById(order.getProductId());
            if (product == null) {
                return Result.error("-1", "商品不存在");
            }
            if (product.getStock() < order.getQuantity()) {
                return Result.error("-1", "库存不足");
            }

            // 生成订单号
            String orderNo = generateOrderNo(order.getUserId());
            order.setOrderNo(orderNo);

            // 计算总价
            order.setTotalPrice(order.getPrice().multiply(BigDecimal.valueOf(order.getQuantity())));

            int result = orderMapper.insert(order);

            if (result > 0) {
                // 更新商品库存
                LOGGER.info("创建订单成功，订单ID：{}，订单号：{}", order.getId(), order.getOrderNo());
                return Result.success(order);
            }
            return Result.error("-1", "创建订单失败");
        } catch (Exception e) {
            LOGGER.error("创建订单失败：{}", e.getMessage());
            return Result.error("-1", "创建订单失败：" + e.getMessage());
        }
    }

    public Result<?> updateOrderStatus(Long id, Integer status) {
        try {
            Order order = orderMapper.selectById(id);
            if (order == null) {
                return Result.error("-1", "未找到订单");
            }

            // 记录原状态
            Integer oldStatus = order.getStatus();
            order.setStatus(status);
            
            // 根据状态更新对应的时间字段
            Timestamp now = Timestamp.valueOf(LocalDateTime.now());
            switch (status) {
                case 1: // 已支付
                    order.setPayTime(now);
                    break;
                case 2: // 已发货
                    order.setDeliveryTime(now);
                    break;
                case 3: // 已完成
                    order.setCompleteTime(now);
                    break;
                case 4: // 已取消
                    order.setCancelTime(now);
                    break;
            }
            
            int result = orderMapper.updateById(order);
            if (result > 0) {
                // 查找该订单的物流信息
                LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Logistics::getOrderId, id);
                Logistics logistics = logisticsMapper.selectOne(queryWrapper);
                
                if (logistics != null) {
                    // 如果订单状态变为已完成，更新物流状态为已签收
                    if (status == 3 && oldStatus != 3) {
                        logistics.setStatus(3); // 3表示已签收
                        logistics.setLastUpdateTime(now);
                        logisticsMapper.updateById(logistics);
                        LOGGER.info("订单已完成，同步更新物流状态为已签收，物流ID：{}", logistics.getId());
                    }
                    // 如果订单状态变为已取消，更新物流状态为异常
                    else if (status == 4 && oldStatus != 4) {
                        logistics.setStatus(4); // 4表示异常
                        logistics.setLastUpdateTime(now);
                        logisticsMapper.updateById(logistics);
                        LOGGER.info("订单已取消，同步更新物流状态为异常，物流ID：{}", logistics.getId());
                    }
                }

                LOGGER.info("更新订单状态成功，订单ID：{}，新状态：{}", id, status);
                return Result.success(order);
            }
            return Result.error("-1", "更新订单状态失败");
        } catch (Exception e) {
            LOGGER.error("更新订单状态失败：{}", e.getMessage());
            return Result.error("-1", "更新订单状态失败：" + e.getMessage());
        }
    }

    public Result<?> deleteOrder(Long id) {
        try {
            deleteRelation(id);
            int result = orderMapper.deleteById(id);

            if (result > 0) {
                LOGGER.info("删除订单成功，订单ID：{}", id);
                return Result.success();
            }
            return Result.error("-1", "删除订单失败");
        } catch (Exception e) {
            LOGGER.error("删除订单失败：{}", e.getMessage());
            return Result.error("-1", "删除订单失败：" + e.getMessage());
        }
    }

    public void deleteRelation(Long id){
        logisticsMapper.delete(new LambdaQueryWrapper<Logistics>().eq(Logistics::getOrderId,id));
    }

    public Result<?> getOrderById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order != null) {
            // 填充关联信息
            order.setUser(userMapper.selectById(order.getUserId()));
            order.setProduct(productMapper.selectById(order.getProductId()));
            


            return Result.success(order);
        }
        return Result.error("-1", "未找到订单");
    }

    public Result<?> getOrdersByUserId(Long userId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        queryWrapper.orderByDesc(Order::getCreatedAt);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if (orders != null && !orders.isEmpty()) {
            // 填充关联信息
            orders.forEach(order -> {
                order.setUser(userMapper.selectById(order.getUserId()));
                order.setProduct(productMapper.selectById(order.getProductId()));
                

            });
            return Result.success(orders);
        }
        return Result.error("-1", "未找到订单");
    }

    public Result<?> getOrdersByPage(Long userId, Long id, String status, Long merchantId, Integer currentPage, Integer size) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(Order::getUserId, userId);
        }
        if (id != null) {
            queryWrapper.eq(Order::getId, id);
        }
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq(Order::getStatus, status);
        }
        if (merchantId != null) {
            List<Product> product = productMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::getMerchantId, merchantId));

            if(!product.isEmpty()){
            List<Long> productIds = product.stream().map(Product::getId).collect(Collectors.toList());
            queryWrapper.in(Order::getProductId, productIds);
            } else {
                Page<Order> page = new Page<>(currentPage, size);
                page.setTotal(0);
                page.setRecords(null);
                return Result.success(page);
            }
        }

        queryWrapper.orderByDesc(Order::getCreatedAt);

        Page<Order> page = new Page<>(currentPage, size);
        Page<Order> result = orderMapper.selectPage(page, queryWrapper);

        // 填充关联信息
        result.getRecords().forEach(order -> {
            order.setUser(userMapper.selectById(order.getUserId()));
            Product product = productMapper.selectById(order.getProductId());
            if(product!=null){
                order.setProduct(product);
                order.setMerchant(userMapper.selectById(product.getMerchantId()));
            }else{
                order.setProduct(null);
                order.setMerchant(null);
            }
            

        });

        return Result.success(result);
    }

    public Result<?> getOrdersByPage(Long userId, Long id, String status, Long merchantId, String username, Integer currentPage, Integer size) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果提供了用户名，先查询对应的用户ID
        if (StringUtils.isNotBlank(username)) {
            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.like(User::getUsername, username)
                            .or()
                            .like(User::getName, username);
            List<User> users = userMapper.selectList(userQueryWrapper);
            if (!users.isEmpty()) {
                // 获取所有匹配用户的ID
                List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
                queryWrapper.in(Order::getUserId, userIds);
            } else {
                // 如果没有找到匹配的用户，返回空结果
                Page<Order> page = new Page<>(currentPage, size);
                page.setTotal(0);
                page.setRecords(null);
                return Result.success(page);
            }
        }
        
        // 保留原有的userId查询条件
        if (userId != null) {
            queryWrapper.eq(Order::getUserId, userId);
        }
        
        if (id != null) {
            queryWrapper.eq(Order::getId, id);
        }
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq(Order::getStatus, status);
        }
        if (merchantId != null) {
            List<Product> product = productMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::getMerchantId, merchantId));

            if(!product.isEmpty()){
            List<Long> productIds = product.stream().map(Product::getId).collect(Collectors.toList());
            queryWrapper.in(Order::getProductId, productIds);
            } else {
                Page<Order> page = new Page<>(currentPage, size);
                page.setTotal(0);
                page.setRecords(null);
                return Result.success(page);
            }
        }

        queryWrapper.orderByDesc(Order::getCreatedAt);

        Page<Order> page = new Page<>(currentPage, size);
        Page<Order> result = orderMapper.selectPage(page, queryWrapper);

        // 填充关联信息
        result.getRecords().forEach(order -> {
            order.setUser(userMapper.selectById(order.getUserId()));
            Product product = productMapper.selectById(order.getProductId());
            if(product!=null){
                order.setProduct(product);
                order.setMerchant(userMapper.selectById(product.getMerchantId()));
            }else{
                order.setProduct(null);
                order.setMerchant(null);
            }
        });

        return Result.success(result);
    }

    public Result<?> deleteBatch(List<Long> ids) {
        try {
            // 检查每个订单是否存在关联记录
            for (Long id : ids) {
                // 检查物流
                deleteRelation(id);
            }

            int result = orderMapper.deleteBatchIds(ids);
            if (result > 0) {
                LOGGER.info("批量删除订单成功，删除数量：{}", result);
                return Result.success();
            }
            return Result.error("-1", "批量删除订单失败");
        } catch (Exception e) {
            LOGGER.error("批量删除订单失败：{}", e.getMessage());
            return Result.error("-1", "批量删除订单失败：" + e.getMessage());
        }
    }

    //余额支付
    @Transactional
    public Result<?> payOrder(Long id){
            Order order = orderMapper.selectById(id);
            if (order == null) {
                return Result.error("-1", "未找到订单");
        } else {
            Product product = productMapper.selectById(order.getProductId());
            if (product != null) {
                if(product.getStock() < order.getQuantity()){
                        return Result.error("-1", "库存不足");
                    }
                product.setSalesCount(product.getSalesCount() + order.getQuantity());
                product.setStock(product.getStock() - order.getQuantity());
                order.setStatus(1); // 已支付
                order.setPayTime(Timestamp.valueOf(LocalDateTime.now())); // 设置支付时间
                User user = userMapper.selectById(order.getUserId());
                user.setBalance(user.getBalance() - order.getTotalPrice().doubleValue());
                userMapper.updateById(user);
                int res = productMapper.updateById(product);

                if(res <= 0){
                    return Result.error("-1", "支付异常");
                    }
                updateOrder(order.getId(), order);
                }
            }
        return Result.success();
    }

    public Result<?> updateOrderAddress(String name, Long id, String address, String phone) {
        try {
            Order order = orderMapper.selectById(id);
            if (order == null) {
                return Result.error("-1", "未找到订单");
            }

            // 检查订单状态，只有未发货的订单才能修改地址
            if (order.getStatus() > 1) {
                return Result.error("-1", "订单已发货，无法修改收货地址");
            }
            order.setRecvName(name);
            order.setRecvAddress(address);
            order.setRecvPhone(phone);
            
            int result = orderMapper.updateById(order);
            if (result > 0) {
                LOGGER.info("更新订单收货信息成功，订单ID：{}", id);
                return Result.success(order);
            }
            return Result.error("-1", "更新订单收货信息失败");
        } catch (Exception e) {
            LOGGER.error("更新订单收货信息失败：{}", e.getMessage());
            return Result.error("-1", "更新订单收货信息失败：" + e.getMessage());
        }
    }
    
    public Result<?> updateOrder(Long id, Order order) {
        try {
            Order existingOrder = orderMapper.selectById(id);
            if (existingOrder == null) {
                return Result.error("-1", "未找到订单");
            }

            // 设置ID确保更新正确的订单
            order.setId(id);
            
            // 保持原有的不可修改字段
            order.setCreatedAt(existingOrder.getCreatedAt());
            order.setUserId(existingOrder.getUserId());
            order.setProductId(existingOrder.getProductId());
            order.setTotalPrice(existingOrder.getTotalPrice());
            
            int result = orderMapper.updateById(order);
            if (result > 0) {
                // 查找该订单的物流信息
                LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Logistics::getOrderId, id);
                Logistics logistics = logisticsMapper.selectOne(queryWrapper);
                
                if (logistics != null) {
                    // 如果订单状态变为已完成，更新物流状态为已签收
                    if (order.getStatus() == 3 && existingOrder.getStatus() != 3) {
                        logistics.setStatus(3); // 3表示已签收
                        logistics.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                        logisticsMapper.updateById(logistics);
                        LOGGER.info("订单已完成，同步更新物流状态为已签收，物流ID：{}", logistics.getId());
                    }
                    // 如果订单状态变为已取消，更新物流状态为异常
                    else if (order.getStatus() == 4 && existingOrder.getStatus() != 4) {
                        logistics.setStatus(4); // 4表示异常
                        logistics.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                        logisticsMapper.updateById(logistics);
                        LOGGER.info("订单已取消，同步更新物流状态为异常，物流ID：{}", logistics.getId());
                    }
                }

                LOGGER.info("更新订单成功，订单ID：{}", id);
                return Result.success(order);
            }
            return Result.error("-1", "更新订单信息失败");
        } catch (Exception e) {
            LOGGER.error("更新订单失败：{}", e.getMessage());
            return Result.error("-1", "更新订单失败：" + e.getMessage());
        }
    }

    public Result<?> getOrderLogistics(Long orderId) {
        try {
            // 检查订单是否存在
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("-1", "未找到订单");
            }

            // 查询物流信息
            LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Logistics::getOrderId, orderId);
            Logistics logistics = logisticsMapper.selectOne(queryWrapper);
            
            if (logistics != null) {
                // 填充关联信息
                logistics.setOrder(order);

                return Result.success(logistics);
            }
            return Result.error("-1", "未找到物流信息");
        } catch (Exception e) {
            LOGGER.error("查询订单物流信息失败：{}", e.getMessage());
            return Result.error("-1", "查询订单物流信息失败：" + e.getMessage());
        }
    }

    /**
     * 订单发货
     * @param orderId 订单ID
     * @param logistics 物流信息
     * @return 处理结果
     */
    @Transactional
    public Result<?> shipOrder(Long orderId, Logistics logistics) {
        try {
            // 检查订单是否存在
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("-1", "订单不存在");
            }
            
            // 检查订单状态是否为已支付
            if (order.getStatus() != 1) {
                return Result.error("-1", "当前订单状态不允许发货，只能发货已支付的订单");
            }
            
            // 设置订单ID
            logistics.setOrderId(orderId);
            
            // 创建物流信息
            Result<?> result = logisticsService.createLogistics(logistics);
            
            if (result.getCode().equals("0")) {
                // 更新订单状态为已发货
                order.setStatus(2); // 2表示已发货
                order.setDeliveryTime(Timestamp.valueOf(LocalDateTime.now())); // 设置发货时间
                orderMapper.updateById(order);
                
                LOGGER.info("订单发货成功，订单ID：{}", orderId);
                return Result.success(result.getData());
            } else {
                return result; // 返回创建物流时的错误信息
            }
        } catch (Exception e) {
            LOGGER.error("订单发货失败：{}", e.getMessage());
            return Result.error("-1", "订单发货失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单统计数据
     * @param merchantId 商户ID (可选)
     * @return 订单统计数据
     */
    public Map<String, Object> getOrderStatistics(Long merchantId) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 构建基础查询条件
            LambdaQueryWrapper<Order> baseQuery = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                // 如果指定了商户ID，则查询该商户的商品相关订单
                List<Product> products = productMapper.selectList(
                    new LambdaQueryWrapper<Product>().eq(Product::getMerchantId, merchantId)
                );
                
                if (products.isEmpty()) {
                    // 如果商户没有商品，则返回空统计
                    statistics.put("totalCount", 0);
                    statistics.put("totalAmount", BigDecimal.ZERO);
                    statistics.put("pendingPaymentCount", 0);
                    statistics.put("paidCount", 0);
                    statistics.put("shippedCount", 0);
                    statistics.put("completedCount", 0);
                    statistics.put("canceledCount", 0);
                    statistics.put("refundedCount", 0);
                    statistics.put("todayOrderCount", 0);
                    statistics.put("todayAmount", BigDecimal.ZERO);
                    statistics.put("monthOrderCount", 0);
                    statistics.put("monthAmount", BigDecimal.ZERO);
                    return statistics;
                }
                
                List<Long> productIds = products.stream().map(Product::getId).collect(Collectors.toList());
                baseQuery.in(Order::getProductId, productIds);
            }
            
            // 查询所有订单
            List<Order> allOrders = orderMapper.selectList(baseQuery);
            
            // 计算总订单数和总金额
            int totalCount = allOrders.size();
            BigDecimal totalAmount = allOrders.stream()
                .filter(order -> order.getTotalPrice() != null)
                .map(Order::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 按状态统计订单数量
            int pendingPaymentCount = 0; // 待支付
            int paidCount = 0;           // 已支付
            int shippedCount = 0;        // 已发货
            int completedCount = 0;      // 已完成
            int canceledCount = 0;       // 已取消
            int refundedCount = 0;       // 已退款
            
            // 今日和本月订单统计
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime todayStart = now.toLocalDate().atStartOfDay();
            LocalDateTime monthStart = now.withDayOfMonth(1).toLocalDate().atStartOfDay();
            
            int todayOrderCount = 0;
            BigDecimal todayAmount = BigDecimal.ZERO;
            int monthOrderCount = 0;
            BigDecimal monthAmount = BigDecimal.ZERO;
            
            for (Order order : allOrders) {
                // 按状态统计
                if (order.getStatus() != null) {
                    switch (order.getStatus()) {
                        case 0: pendingPaymentCount++; break;
                        case 1: paidCount++; break;
                        case 2: shippedCount++; break;
                        case 3: completedCount++; break;
                        case 4: canceledCount++; break;
                        case 5: refundedCount++; break;
                    }
                }
                
                // 时间相关统计
                if (order.getCreatedAt() != null) {
                    LocalDateTime createdAt = order.getCreatedAt().toLocalDateTime();
                    
                    // 今日订单
                    if (createdAt.isAfter(todayStart) || createdAt.isEqual(todayStart)) {
                        todayOrderCount++;
                        if (order.getTotalPrice() != null) {
                            todayAmount = todayAmount.add(order.getTotalPrice());
                        }
                    }
                    
                    // 本月订单
                    if (createdAt.isAfter(monthStart) || createdAt.isEqual(monthStart)) {
                        monthOrderCount++;
                        if (order.getTotalPrice() != null) {
                            monthAmount = monthAmount.add(order.getTotalPrice());
                        }
                    }
                }
            }
            
            // 整合统计结果
            statistics.put("totalCount", totalCount);
            statistics.put("totalAmount", totalAmount);
            statistics.put("pendingPaymentCount", pendingPaymentCount);
            statistics.put("paidCount", paidCount);
            statistics.put("shippedCount", shippedCount);
            statistics.put("completedCount", completedCount);
            statistics.put("canceledCount", canceledCount);
            statistics.put("refundedCount", refundedCount);
            statistics.put("todayOrderCount", todayOrderCount);
            statistics.put("todayAmount", todayAmount);
            statistics.put("monthOrderCount", monthOrderCount);
            statistics.put("monthAmount", monthAmount);
            
            return statistics;
        } catch (Exception e) {
            LOGGER.error("获取订单统计数据失败：{}", e.getMessage());
            Map<String, Object> errorStats = new HashMap<>();
            errorStats.put("error", "获取订单统计数据失败");
            return errorStats;
        }
    }
} 